import type { Reactive } from 'vue';

import type { VxeTableGridOptions } from '@vben/plugins/vxe-table';

import type { VbenFormSchema } from '#/adapter/form';
import type { OnActionClickFn } from '#/adapter/vxe-table';
import type { DictApi, ToolApi } from '#/api';

import { reactive, ref } from 'vue';

import { z } from '#/adapter/form';
import { DictResp, getAutoCode, getSelectOptions, tmToolTypeAll } from '#/api';

const switchValue = ref('');
const toolTypeList = reactive<DictApi.SelectOption[]>([]);
const codeFlagMap = ref({});

tmToolTypeAll().then((resList) => {
  if (resList.data) {
    getSelectOptions(resList.data, 'toolTypeName', 'toolTypeId').then((res) => {
      // 将两个数组合并
      if (res && Array.isArray(res.options)) {
        toolTypeList.push(...res.options);
      }
      // 将resList.data数组里面的codeFlag字段与toolTypeId字段做一个映射，将codeFlag字段的值作为key，toolTypeId字段的值作为value
      const codeFlagMapId = resList.data?.reduce(
        (acc, item) => {
          acc[item.toolTypeId] = item.codeFlag === 'Y';
          return acc;
        },
        {} as Record<number, boolean>,
      );
      codeFlagMap.value = codeFlagMapId;
    });
  }
});

const mes_tool_status = reactive<DictApi.SelectOption[]>([]);
const mes_mainten_type = reactive<DictApi.SelectOption[]>([]);

DictResp(['mes_tool_status', 'mes_mainten_type']).then((res) => {
  // 将两个数组合并
  if (res.mes_mainten_type) {
    mes_mainten_type.push(...res.mes_mainten_type);
  }
  if (res.mes_tool_status) {
    mes_tool_status.push(...res.mes_tool_status);
  }
});
/**
 * 获取编辑表单的字段配置
 */
export function useSchema(): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'toolId',
      dependencies: {
        triggerFields: ['toolId'],
        show: false,
      },
    },
    {
      component: 'Input',
      fieldName: 'toolCode',
      label: '工装夹具编号',
      rules: 'required',
      formItemClass: 'col-span-1',
      componentProps: {
        placeholder: '请输入工装夹具编号',
      },
      dependencies: {
        triggerFields: ['switch'],
        trigger(values) {
          values.toolCode = switchValue;
        },
      },
    },
    {
      component: 'Switch',
      fieldName: 'switch',
      label: '自动生成',
      formItemClass: 'col-span-1',
      componentProps: {
        defaultValue: 0,
        onChange: (e: boolean) => {
          if (e) {
            getAutoCode('TOOL_CODE').then((res) => {
              switchValue.value = res.data;
            });
          } else {
            switchValue.value = '';
          }
        },
      },
      dependencies: {
        triggerFields: ['toolId'],
        show(values) {
          return !values.toolId && true;
        },
      },
    },
    {
      component: 'Input',
      fieldName: 'toolName',
      label: '工装夹具名称',
      rules: 'required',
      componentProps: {
        placeholder: '请输入工装夹具名称',
      },
      formItemClass: 'col-span-2 col-start-1',
    },
    {
      component: 'Select',
      rules: 'required',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: toolTypeList,
        placeholder: '请选择类型',
        showSearch: true,
      },
      fieldName: 'toolTypeId',
      label: '工装夹具类型',
      formItemClass: 'col-span-2 col-start-1',
    },
    {
      component: 'Input',
      fieldName: 'codeFlag',
      label: '隐藏类型codeFlag',
      dependencies: {
        triggerFields: ['toolTypeId'],
        show: false,
        trigger(values) {
          values.codeFlag = (
            codeFlagMap.value as Record<number | string, boolean>
          )[values.toolTypeId]
            ? 'Y'
            : 'N';
        },
      },
    },
    {
      component: 'Input',
      fieldName: 'spec',
      label: '型号',
      componentProps: {
        placeholder: '请输入型号',
      },
      formItemClass: 'col-span-2 col-start-1',
    },
    {
      component: 'Input',
      fieldName: 'brand',
      label: '品牌',
      componentProps: {
        placeholder: '请输入型号',
      },
      formItemClass: 'col-span-2 col-start-1',
    },
    {
      component: 'ElInputNumber',
      fieldName: 'quantity',
      defaultValue: 0,
      label: '数量',
      componentProps: {
        min: 0,
        class: 'w-full',
      },
      emptyStateValue: null,
      formItemClass: 'col-span-1',
      dependencies: {
        triggerFields: ['toolTypeId'],
        show(values) {
          // 上来默认展示，后续根据toolType的值来判断是否展示
          return (
            !values.toolTypeId ||
            (codeFlagMap.value as Record<number | string, boolean>)[
              values.toolTypeId
            ] === false
          );
        },
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'quantity',
      defaultValue: 0,
      label: '数量',
      componentProps: {
        min: 0,
        class: 'w-full',
        readonly: true,
      },
      emptyStateValue: null,
      formItemClass: 'col-span-1',
      dependencies: {
        triggerFields: ['toolTypeId'],
        show(values) {
          // 后续根据toolType的值来判断是否展示
          const isY =
            (codeFlagMap.value as Record<number | string, boolean>)[
              values.toolTypeId
            ] === true;
          if (isY) {
            values.quantity = 1;
            values.quantityAvail = 1;
          }
          return isY;
        },
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'quantityAvail',
      defaultValue: 0,
      label: '可用数量',
      componentProps: {
        min: 0,
        class: 'w-full',
        readonly: true,
      },
      emptyStateValue: null,
      formItemClass: 'col-span-2',
      dependencies: {
        triggerFields: ['toolTypeId'],
        show(values) {
          return (
            (codeFlagMap.value as Record<number | string, boolean>)[
              values.toolTypeId
            ] === true
          );
        },
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'quantityAvail',
      defaultValue: 0,
      label: '可用数量',
      componentProps: {
        min: 0,
        class: 'w-full',
        readonly: false,
      },
      emptyStateValue: null,
      formItemClass: 'col-span-2',
      help: '可用数量不能大于数量',
      dependencies: {
        triggerFields: ['toolTypeId', 'quantityAvail', 'quantity'],
        show(values) {
          return (
            !values.toolTypeId ||
            (codeFlagMap.value as Record<number | string, boolean>)[
              values.toolTypeId
            ] === false
          );
        },
        rules(values) {
          return z.number().max(values.quantity, {
            message: `可用数量不能大于数量：${values.quantity}`,
          });
        },
      },
    },
    {
      component: 'Select',
      defaultValue: 'REGULAR',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: mes_mainten_type,
        placeholder: '请选择类型',
        showSearch: true,
      },
      fieldName: 'maintenType',
      label: '保养维护类型',
      formItemClass: 'col-span-1',
    },
    {
      component: 'DatePicker',
      fieldName: 'nextMaintenDate',
      defaultValue: null,
      label: '下次保养日期',
      formItemClass: 'col-span-1 col-start-1',
      dependencies: {
        triggerFields: ['maintenType'],
        show(values) {
          return values.maintenType !== 'USAGE';
        },
      },
    },

    {
      component: 'Input',
      fieldName: 'nextMaintenPeriod',
      label: '下次保养周期',
      formItemClass: 'col-span-1 col-start-1',
      dependencies: {
        triggerFields: ['maintenType'],
        show(values) {
          return values.maintenType === 'USAGE';
        },
      },
    },
    {
      component: 'CheckboxGroup',
      disabled: true,
      defaultValue: 'STORE',
      componentProps: {
        name: 'cname',
        options: mes_tool_status,
      },
      fieldName: 'status',
      label: '状态',
      formItemClass: 'col-span-1 col-start-3',
    },

    {
      component: 'Textarea',
      componentProps: {
        placeholder: '请输入备注信息',
        maxLength: 50,
        rows: 3,
        showCount: false,
      },
      fieldName: 'remark',
      label: '备注',
      emptyStateValue: null,
      formItemClass: 'col-span-3',
    },
  ];
}

/**
 * 获取表格列配置
 * @param onView 表格点击函数
 * @param mes_mainten_type 保养维护类型
 * @param mes_tool_status 工具状态
 * @param _onActionClick 表格操作按钮点击事件
 */
export function useColumns(
  onView: (param: ToolApi.Row) => void,
  mes_mainten_type: Reactive<DictApi.SelectOption[]>,
  mes_tool_status: Reactive<DictApi.SelectOption[]>,
  _onActionClick?: OnActionClickFn<ToolApi.Row>,
): VxeTableGridOptions<ToolApi.Row>['columns'] {
  return [
    {
      field: 'checkbox',
      fixed: 'left',
      type: 'checkbox',
    },
    {
      field: 'toolCode',
      title: '编号',
      width: 50,
    },
    {
      field: 'toolName',
      title: '名称',
      cellRender: { name: 'CellButtonInfo', props: { onClick: onView } },
      width: 120,
    },

    {
      field: 'brand',
      title: '品牌',
      width: 80,
    },
    {
      field: 'spec',
      title: '型号',
      width: 80,
    },
    {
      field: 'toolTypeName',
      title: '类型',
      width: 80,
    },
    {
      field: 'quantity',
      title: '库存数量',
    },
    {
      title: '可用数量',
      field: 'quantityAvail',
      width: 80,
    },
    {
      field: 'maintenType',
      title: '保养维护类型',
      formatter: ({ cellValue }) => {
        const item = mes_mainten_type.find((item) => item.value === cellValue);
        return item?.label || '无';
      },
    },
    {
      title: '下次保养周期',
      field: 'nextMaintenPeriod',
    },
    {
      title: '下次保养日期',
      field: 'nextMaintenDate',
    },
    {
      title: '状态',
      field: 'status',
      formatter: ({ cellValue }) => {
        const item = mes_tool_status.find((item) => item.value === cellValue);
        return item?.label || '无';
      },
    },
    {
      field: 'action',
      title: '操作',
      width: 150,
      fixed: 'right',
      align: 'center',
      slots: { default: 'action' },
    },
  ];
}
